import React, { Component } from 'react';
import { View, StyleSheet, Text, Animated, Easing, SafeAreaView, Dimensions,Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import {inject,observer } from "mobx-react";
import axios from 'axios';
import {Dialog} from '@rneui/themed';

const { width, height } = Dimensions.get('window');

@inject("rootStore") // 注入 用来获取 全局数据的
@observer //  当全局发生改变了  组件的重新渲染 从而显示最新的数据
class BarCodePage extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            time:0,
            visible2: false,
            transCode: '', // 条码
            typeCode: '', // 条码类型
            showCode: true,
            animateCode: new Animated.Value(0), // 初始化动画值
        }
    }

    componentDidMount() {
        this.startAnimation();
        console.log('进入-------', this.state.showCode);
    }

    componentWillUnmount() {
        // 在组件销毁时停止动画 
        this.state.animateCode.stopAnimation();
    }  

    //启动计时器
    startTick() {
        this.timerID = setInterval(
            () => this.tick(),
            1000 // 每秒触发一次
        );
        }
    
    //计时器
    tick() {
    this.setState({
        time: this.state.time + 1
    });
    }

    //关闭加载
    toggleDialog2 = () => {
        clearInterval(this.timerID);
        this.setState({time:0})
        this.setState({visible2:false})
      };
    // 动画开始
    startAnimation() {
        this.state.animateCode.setValue(0);
        Animated.timing(this.state.animateCode, {
            toValue: 1,
            duration: 2500,
            easing: Easing.linear,
            useNativeDriver: true, // 使用原生驱动
        }).start(() => this.startAnimation());
    }

    barcodeReceived=async(e)=> {
        if (this.state.showCode) {
            console.log(e);
            this.setState({
                transCode: e.data,
                typeCode: e.type,
                showCode: false
            });
            if (e.data) {
                this.startTick();
                this.setState({visible2:true})
                let data;
                try {
                    const response = await axios.get(`${this.props.rootStore.ip}/stm/${e.data}`);
                    // 处理响应数据
                    console.log(response.data); // 这里假设服务器返回的数据是 JSON 格式的
                    if(response.data.code==200){
                        data=response.data.data
                        this.props.rootStore.pg=data.mxmc;
                        this.props.navigation.replace('TestPage', { data });
                    }else{
                        if(this.state.visible2){
                            this.toggleDialog2();
                            Alert.alert('错误', response.data.msg, [
                                {
                                  text: '确定',
                                  onPress: () => {
                                    this.props.navigation.replace('scan');

                                  }
                                }
                              ]);
                            // this.props.navigation.goBack()
                          }else{
                            return;
                          }
                    }
        
                } catch (error) {
                    if(this.state.visible2){
                        this.toggleDialog2();
                        Alert.alert('网络错误', '请检查网络！');
                        this.props.navigation.goBack()
                        this.cameraRef.current.scanBarcode();
                        // 处理请求错误
                        console.error('Error while fetching data:', error);
                      }else{
                        return;
                      }
                }
            }
        }
    }

    render() { 
        return ( 
            <SafeAreaView style={styles.container}>
                <RNCamera
                    style={styles.scan_camera}
                    captureAudio={false}
                    onBarCodeRead={this.barcodeReceived.bind(this)}
                    androidCameraPermissionOptions={{
                        title: '相机权限',
                        message: '我们需要您的相机权限来进行扫描操作',
                        buttonPositive: '同意',
                        buttonNegative: '拒绝',
                    }}
                >
                    <View style={styles.scan_cont_box}>
                        <View style={styles.scan_cont_circle}>
                            <Animated.View style={{
                                alignItems: 'center',
                                transform: [{
                                    translateY: this.state.animateCode.interpolate({
                                        inputRange: [0, 1],
                                        outputRange: [0, 200]
                                    })
                                }]
                            }}>
                                <Text style={styles.scan_circle_init}></Text>
                            </Animated.View>
                        </View>
                    </View>
                    <Dialog isVisible={this.state.visible2} onBackdropPress={this.toggleDialog2}>
                    <Dialog.Title title={"正在识别，已等待" + this.state.time +"秒"}/>
                        <Dialog.Loading />
                    </Dialog>
                    <View style={styles.scan_info_box}>
                        <Text style={styles.scan_info}>将条形码放入框内，即可自动扫描</Text>
                    </View>
                </RNCamera>
            </SafeAreaView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    scan_camera: {
        flex: 1,
        height: height,
    },
    scan_cont_box: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0,0,0,0.3)',
    },
    scan_cont_circle: {
        width: 260,
        height: 260,
        borderWidth: 1,
        borderColor: '#919191',
        backgroundColor: 'rgba(255,255,255,0.1)'
    },
    scan_circle_init: {
        width: 250,
        height: 1,
        backgroundColor: '#00ff00'
    },
    scan_info_box: {
        height: 100,
        backgroundColor: 'rgba(0,0,0,0.3)',
        alignItems: 'center',
        width: width,
    },
    scan_info: {
        color: '#fff'
    },
    info: {
        width: width,
        height: 80,
        backgroundColor: '#fff',
        paddingLeft: 10,
        paddingBottom: 5,
        justifyContent: 'space-around',
    },
});

export default BarCodePage;
